package com.my.lucky7.common;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class LocalCache {
    private final Map<String, CacheEntry> cacheMap;

    public LocalCache() {
        this.cacheMap = new HashMap<>();
    }

    // 添加或更新缓存
    public void put(String key, Object value, long ttl) {
        long expiryTime = System.currentTimeMillis() + ttl;
        cacheMap.put(key, new CacheEntry(value, expiryTime));
    }

    // 获取缓存值
    public Object get(String key) {
        CacheEntry entry = cacheMap.get(key);
        if (entry != null && !isExpired(entry)) {
            return entry.value;
        }
        cacheMap.remove(key); // 移除过期的缓存
        return null;
    }

    // 检查缓存是否过期
    private boolean isExpired(CacheEntry entry) {
        return System.currentTimeMillis() > entry.expiryTime;
    }

    // 清除所有缓存
    public void clear() {
        cacheMap.clear();
    }

    // 缓存条目内部类
    private static class CacheEntry {
        Object value;
        long expiryTime;

        CacheEntry(Object value, long expiryTime) {
            this.value = value;
            this.expiryTime = expiryTime;
        }
    }
}
